package main

import (
	"distributed/conf"
	"distributed/controllers"
	"distributed/db"
	"distributed/storage"
	"fmt"
	"golang.org/x/net/websocket"
	"net/http"
	"net/rpc"
)

func init() {
	conf.LoadConfig()
	db.DBConnect()
	storage.ViewChanInit()
}

func main() {
	//  todo: rpc-server -> server
	if err := rpc.Register(&storage.Store{}); err != nil {
		panic(err)
	}
	rpc.HandleHTTP()

	go func() {
		serverMux := http.NewServeMux()
		serverMux.HandleFunc("/index", controllers.Index)
		serverMux.HandleFunc("/search", controllers.Search)
		serverMux.HandleFunc("/realtime", controllers.RealTime)
		serverMux.Handle("/comment", websocket.Handler(controllers.Comment))
		fmt.Println("[ http server running in :8080 ]")
		if err := http.ListenAndServe(":8080", serverMux); err != nil {
			panic(err)
		}
	}()

	//http.HandleFunc("/ws",controllers.WebSocket)
	fmt.Printf("[ rpc server running in %v ]\n", conf.GetConfig("storage_port"))
	if err := http.ListenAndServe(conf.GetConfig("storage_port"), nil); err != nil {
		panic(err)
	}
}
